package com.stylefeng.guns.modular.yjya.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.stylefeng.guns.common.persistence.dao.AccidentProcessMapper;
import com.stylefeng.guns.common.persistence.dao.CounterplanAccidentMapper;
import com.stylefeng.guns.common.persistence.model.AccidentProcess;
import com.stylefeng.guns.common.persistence.model.CounterplanAccident;
import com.stylefeng.guns.modular.yjya.service.ICounterplanAccidentService;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.lang.reflect.InvocationTargetException;
import java.util.List;

/**
 * <p>
 * 预案处置流程表 服务实现类
 * </p>
 *
 * @author xuziyang
 * @since 2018-01-22
 */
@Service
public class CounterplanAccidentServiceImpl extends ServiceImpl<CounterplanAccidentMapper, CounterplanAccident> implements ICounterplanAccidentService {

    @Autowired
    private AccidentProcessMapper accidentMapper;

    @Override
    @Transactional
    public void insert(Integer counterplanId, Integer[] accidentIds) {
        Wrapper wrapper = new EntityWrapper<CounterplanAccident>();
        wrapper.eq("id", counterplanId);
        super.delete(wrapper);

        int i = 1;
        for (Integer accidentId : accidentIds) {
            AccidentProcess accidentProcess = accidentMapper.selectById(accidentId);
            if (accidentProcess == null) {
                //todo
//                throw
            }
            CounterplanAccident counterplanAccident = new CounterplanAccident();
            try {
                BeanUtils.copyProperties(counterplanAccident, accidentProcess);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
            counterplanAccident.setNum(i);
            counterplanAccident.setId(counterplanId);
            super.insert(counterplanAccident);
            i++;
        }
    }

    public String getHtml(Integer counterplanId) {
        Wrapper wrapper = new EntityWrapper<CounterplanAccident>();
        wrapper.eq("id", counterplanId);
        wrapper.orderBy("num");
        List<CounterplanAccident> list = selectList(wrapper);
        StringBuilder sb = new StringBuilder();
        for (CounterplanAccident ca : list) {
            sb.append(ca.toString() + "<br/>");
        }
        return sb.toString();
    }

    @Override
    public void deleteByCounterplanId(Integer counterplanId) {
        Wrapper<CounterplanAccident> wrapper = new EntityWrapper<>();
        wrapper.eq("id", counterplanId);
        this.delete(wrapper);
    }
}
